package com.hsy.swu.other.commentsection

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hsy.swu.clouddb.Comment
import com.hsy.swu.clouddb.LeanCloudHelper
import com.hsy.swu.databinding.OtherCommentBottomDialogRvItemBinding
import com.hsy.swu.hsyutils.setFont

class CommentBottomDialogAdapter :
    RecyclerView.Adapter<CommentBottomDialogAdapter.CommentBottomDialogViewHolder>() {
    var mItemList = mutableListOf<Comment>()
        @SuppressLint("NotifyDataSetChanged")
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    private var likeClickListener: ((OtherCommentBottomDialogRvItemBinding, Comment) -> Unit)? =
        null

    fun setLikeClickListener(listener: (OtherCommentBottomDialogRvItemBinding, Comment) -> Unit) {
        likeClickListener = listener
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CommentBottomDialogViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = OtherCommentBottomDialogRvItemBinding.inflate(layoutInflater, parent, false)
        return CommentBottomDialogViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return mItemList.size
    }

    override fun onBindViewHolder(holder: CommentBottomDialogViewHolder, position: Int) {
        holder.bind(position)
    }

    inner class CommentBottomDialogViewHolder(private val binding: OtherCommentBottomDialogRvItemBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            binding.setFont()
            val comment = mItemList[position]

            // 点赞过这条就显示 1f
            binding.like.progress = if (comment.isCurrentUserLikeThisComment()) 1f else 0f
            // newLikeCounts为空则赋值
            if (comment.newLikeCounts == null) comment.newLikeCounts = comment.likeCounts

            binding.apply {
                likeCounts.text = comment.newLikeCounts.toString()
                commentatorNickName.text = comment.commentatorNickName
                floor.text = "第${position + 1}楼"
                time.text = LeanCloudHelper.getInstance()?.parseUpdateAt(comment.createdAt)
                content.text = comment.content
            }

            binding.like.setOnClickListener {
                likeClickListener?.invoke(binding, comment)
            }
        }
    }
}